#include "Subsystems/BlockBehaviors/SubsystemCarpetBlockBehavior.h"
#include "GameRandom.hpp"
#include "Subsystems/SubsystemWeather.h"
#include "Subsystems/SubsystemTerrain.h"
#include "Managers/BlocksManager.h"
#include "Log.h"
#include "GameSingleton.h"


namespace PocketSurvival
{
    SubsystemCarpetBlockBehavior::SubsystemCarpetBlockBehavior() {}
    

    void SubsystemCarpetBlockBehavior::onPoll(int32_t value, int32_t x, int32_t y, int32_t z)
    {
        if (GameSingleton::gameRandom->getFloat(0.0f, 1.0f) < 0.25f)
        {
            PrecipitationShaftInfo precipitationShaftInfo = m_weather->getPrecipitationShaftInfo(x, z);
            if (precipitationShaftInfo.Intensity > 0.0f && y >= precipitationShaftInfo.YLimit - 1)
            {
                m_terrain->destroyCell(0, x, y, z, 0, true);
            }
        }
    }

    void SubsystemCarpetBlockBehavior::onNeighborBlockChanged(int32_t x, int32_t y, int32_t z, int32_t neighborX, int32_t neighborY, int32_t neighborZ)
    {
        int32_t cellContents = m_terrain->getCellContents(x, y - 1, z);
        if (GameSingleton::blocksManager->blocks[cellContents]->IsTransparent)
        {
            m_terrain->destroyCell(0, x, y, z, 0, false);
        }
    }

    void SubsystemCarpetBlockBehavior::load(const nlohmann::json &json)
    {
        m_weather = GameSingleton::singletonPtr->getSingleton<SubsystemWeather>();
        m_terrain = GameSingleton::singletonPtr->getSingleton<SubsystemTerrain>();
    }

    static const std::string subsystemName = "CarpetBlockBehavior";
    const std::string &SubsystemCarpetBlockBehavior::getName() const
    {
        return subsystemName;
    }
}
